/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jhu.profiteer.admin;

import java.io.IOException;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jhu.profiteer.data.Account;
import jhu.profiteer.data.AccountJpaController;
import jhu.profiteer.data.exceptions.NonexistentEntityException;

/**
 *
 * @author Jeremy
 */
public class AccountServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
      String submit = request.getParameter("submit");

      if(null == submit)
      {
        this.getServletContext().getRequestDispatcher("/admin/accounts").forward(request, response);
        return;
      }

      HttpSession session = request.getSession();
      Vector<String> notices = (Vector<String>)session.getAttribute("notices");

      if(submit.equalsIgnoreCase("Create"))
      {
        boolean save = true;
        String url = "/admin/accounts";
        String name = request.getParameter("name");

        if((null == name) || name.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply an account name.");
          save = false;
          url = "/admin/account";
        }

        String administrator = request.getParameter("administrator");

        if((null == administrator) || administrator.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply an account administrator status.");
          save = false;
          url = "/admin/account";
        }

        String password = request.getParameter("password");

        if((null == password) || password.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply an account password.");
          save = false;
          url = "/admin/account";
        }

        String email = request.getParameter("email");

        if((null == email) || email.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply an account email address.");
          save = false;
          url = "/admin/account";
        }

        if(save)
        {
          Account a = new Account();
          a.setName(name);
          a.setAdministrator(Boolean.valueOf(administrator).booleanValue());
          a.setDamaged(false);
          a.setPassword(password);
          a.setEmailAddress(email);
          AccountJpaController jc = new AccountJpaController();
          jc.create(a);
        }

        if(null != notices) session.setAttribute("notices", notices);
        this.getServletContext().getRequestDispatcher(url).forward(request, response);
      }
      else if(submit.equalsIgnoreCase("Update"))
      {
        boolean save = true;
        String idParam = request.getParameter("accountId");
        String url = "/admin/accounts";

        if((null == idParam) || idParam.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply an account ID.");
          save = false;
        }

        String name = request.getParameter("name");

        if((null == name) || name.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply an account name.");
          save = false;
          url = "/admin/account?accountId=" + idParam;
        }

        String administrator = request.getParameter("administrator");

        if((null == administrator) || administrator.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply an account administrator status.");
          save = false;
          url = "/admin/account?accountId=" + idParam;
        }

        String damaged = request.getParameter("damaged");

        if((null == damaged) || damaged.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply an account damaged status.");
          save = false;
          url = "/admin/account?accountId=" + idParam;
        }

        String email = request.getParameter("email");

        if((null == email) || email.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply an account email address.");
          save = false;
          url = "/admin/account?accountId=" + idParam;
        }

        if(save)
        {
          AccountJpaController jc = new AccountJpaController();
          Account a = jc.findAccount(Long.parseLong(idParam));

          if(null != a)
          {
            a.setName(name);
            a.setAdministrator(Boolean.valueOf(administrator).booleanValue());
            a.setDamaged(Boolean.valueOf(damaged).booleanValue());
            a.setEmailAddress(email);

            try
            {
              jc.edit(a);
            }
            catch(NonexistentEntityException ex)
            {
              if(null == notices) notices = new Vector<String>();
              notices.add("No account with that ID exists.");
            }
            catch(Exception ex)
            {
              if(null == notices) notices = new Vector<String>();
              notices.add("Error editing account.");
            }
          }
          else
          {
            if(null == notices) notices = new Vector<String>();
            notices.add("No account with that ID exists.");
          }
        }

        if(null != notices) session.setAttribute("notices", notices);
        this.getServletContext()
                .getRequestDispatcher(url)
                .forward(request, response);
      }
      else if(submit.equalsIgnoreCase("Delete"))
      {
        AccountJpaController jc = new AccountJpaController();
        String param = request.getParameter("accountId");
        Long id = 0L;

        if((null == param) || (param.isEmpty()))
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply a account ID.");
        }
        else
        {
          id = Long.parseLong(param);

          try
          {
            jc.destroy(id);
            if(null == notices) notices = new Vector<String>();
            notices.add("You have successfully deleted the account");
          }
          catch (NonexistentEntityException ex)
          {
            if(null == notices) notices = new Vector<String>();
            notices.add("Invalid account ID!");
          }
        }

        if(null != notices) session.setAttribute("notices", notices);
        this.getServletContext().getRequestDispatcher("/admin/accounts").forward(request, response);
      }
      else if(submit.equalsIgnoreCase("Change Password"))
      {
        AccountJpaController jc = new AccountJpaController();
        String param = request.getParameter("accountId");
        String url = "/admin/accounts";

        if(null == jc)
        {
          jc = new AccountJpaController();
          session.setAttribute("accController", jc);
        }

        if((null == param) || (param.isEmpty()))
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply a valid account ID.");
          if(null != notices) session.setAttribute("notices", notices);
          this.getServletContext().getRequestDispatcher(url).forward(request, response);
        }

        Account a = jc.findAccount(Long.parseLong(param));

        if(null == a)
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply a valid account ID.");
          if(null != notices) session.setAttribute("notices", notices);
          this.getServletContext().getRequestDispatcher(url).forward(request, response);
        }

        boolean process = true;
        String currentPassword = request.getParameter("currentPassword");
        String newPassword = request.getParameter("newPassword");
        String confirmPassword = request.getParameter("confirmPassword");

        if((null == currentPassword) || currentPassword.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply the current password.");
          url = "/admin/changePassword";
          process = false;
        }

        if(!a.verifyPassword(currentPassword))
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("Invalid password!");
          url = "/admin/changePassword";
          process = false;
        }

        if((null == newPassword) || newPassword.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply a new password.");
          url = "/admin/changePassword";
          process = false;
        }

        if((null == confirmPassword) || confirmPassword.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must confirm the new password.");
          url = "/admin/changePassword";
          process = false;
        }

        if(process)
        {
          if(!newPassword.equals(confirmPassword))
          {
            if(null == notices) notices = new Vector<String>();
            notices.add("The new and confirm passwords do not match!");
            url = "/admin/changePassword";
          }
          else
          {
            a.setPassword(newPassword);

            try
            {
              jc.edit(a);
              if(null == notices) notices = new Vector<String>();
              notices.add("Password successfully changed!");
            }
            catch(NonexistentEntityException ex)
            {
              if(null == notices) notices = new Vector<String>();
              notices.add("No account with that ID exists.");
            }
            catch(Exception ex)
            {
              if(null == notices) notices = new Vector<String>();
              notices.add("Error editing account.");
            }
          }
        }

        if(null != notices) session.setAttribute("notices", notices);
        this.getServletContext().getRequestDispatcher(url).forward(request, response);
      }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
